// pages/my/my.js
import api from '../../utils/api.js'
var app = getApp();
import { HTTP } from '../../utils/http.js'
import { config } from '../../utils/config'
let http = new HTTP()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        is_auth: false,
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        avatarUrl: "",
        nickName: "",
        crown: false,
        has: 0,
        history: [], //历史购买
        new_gold_gebi_num: 0,
        new_gebi_num: 0,
        new_integral_num: 0,
        captureTouch: 'captureTouch',
        gegou_num: 0,
        jifen_num: 0,
        imgUrl: config.imgUrl,
    },
    onLaunch: function () {
        this.checkUpdateVersion()
    },
    /* 生命周期函数--监听页面加载 */
    onLoad: function (options) {
        if (wx.getStorageSync('is_member')) {
            if (wx.getStorageSync('is_member') == 1) {
                this.setData({
                    crown: true
                })
            } else {
                this.setData({
                    crown: false
                })
            }
        }
        this.getCookBook();
    },
    onShow: function () {
        let user_token = wx.getStorageSync('token')
        let user_name = wx.getStorageSync('nickName');
        wx.wg_util.refreshShopCarBadge();
        let my_is_auth = wx.getStorageSync('is_auth')
        if (my_is_auth) {
            console.log("~~~~~~~~~~~~~~~")
            console.log(my_is_auth)
            this.setData({
                is_auth: true,
                captureTouch: '',
                nickName: wx.getStorageSync("nickName"),
                avatarUrl: wx.getStorageSync("avatarUrl"),
            });
        }
        wx.removeStorage({ key: 'select-goods', })
        let user_id = wx.getStorageSync('user_id');
        console.log(user_token)
        if (user_token && user_name) {
            //获取歌豆积分
            this.getCoins(user_token)
        }
        if (user_id) {
            this.getHistroyBooks(user_id)
            this.getGoldGebiNumAdd(user_id)
            this.getGebiNumAdd(user_id)
            this.getIntegralAdd(user_id)
            //获取用户的新消息数量
            this.getClientNewNum(user_id)
        }

        let is_member = wx.getStorageSync('is_member');
        if (is_member == 1) {
            this.setData({
                is_member
            })
        }


        //启动动画
        // this.bubbleAnimation()
    },
    checkUpdateVersion() {
        //判断微信版本是否兼容小程序更新机制API使用
        if (wx.canIUse('getUpdateManager')) {
            //创建 UpdateManager 实例
            const updateManager = wx.getUpdateManager();
            console.log('是否进入模拟更新');
            //检测版本更新
            updateManager.onCheckForUpdate(function (res) {
                console.log('是否获取版本');
                // 请求完新版本信息的回调
                if (res.hasUpdate) {
                    //监听小程序有版本更新事件
                    updateManager.onUpdateReady(function () {
                        //TODO 新的版本已经下载好，调用 applyUpdate 应用新版本并重启 （ 此处进行了自动更新操作）
                        updateManager.applyUpdate();
                    })
                    updateManager.onUpdateFailed(function () {
                        // 新版本下载失败
                        wx.showModal({
                            title: '已经有新版本喽~',
                            content: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开哦~',
                        })
                    })
                }
            })
        } else {
            //TODO 此时微信版本太低（一般而言版本都是支持的）
            wx.showModal({
                title: '溫馨提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },

    /*点击菜谱列表*/
    showCook(e) {

        let address = wx.getStorageSync('address');
        if (!address) {
            app.login();
            return;
        }
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: "/pages/video/video?id=" + id
        })
    },
    toMoneyDetail() {
        wx.navigateTo({
            url: '/pages/moneyDetail/moneyDetail'
        })
    },
    /*更多菜谱*/
    moreCook() {
        let address = wx.getStorageSync('address');
        if (!address) {
            app.login();
            return;
        }
        wx.navigateTo({
            url: '/pages/myCook/myCook'
        })
    },

    /*获取菜谱*/
    getCookBook() {
        let that = this
        http.request({
            url: api.mycookbook,
            method: "GET",
            data: {},
            success: (res) => {

                if (res.code == 200) {
                    this.setData({
                        recommend: res.data
                    })
                }
            }
        })
    },

    getInfo(obj, url) {
        return new Promise((resolve, reject) => {
            http.request({
                url: url,
                data: obj,
                success: res => {
                    resolve(res);
                }
            })
        })
    },
    topDingdan() {
        wx.navigateTo({
            url: '/pages/dingdan/dingdan',
        })
    },
    toMemberJifen() {
        wx.navigateTo({
            url: '/pages/gedouDetail/gedouDetail',
        })
    },
    ruzhuDanpu() {//入主店铺页面
        wx.navigateTo({
            url: '/pages/ruzhu/ruzhu',
        })
    },
    tomenber() {
        wx.navigateTo({
            url: '/pages/menber-quanyi/menber-quanyi',
        })
    },
    dizhi() {
        this.getCityId();
        wx.navigateTo({
            url: '/pages/allDizhi/allDizhi?order=0',
        })
    },
    toDaili() {
        wx.navigateTo({
            url: '/pages/daili/daili',
        })
    },
    //联系客服
    toKefu() {
        wx.navigateTo({
            url: '/pages/kefu-complaint/kefu-complaint',
        })
    },
    goToHelp() {
        wx.navigateTo({
            url: '/pages/help/help',
        })
    },
    toHistory() {
        var history = JSON.stringify(this.data.history)
        wx.navigateTo({
            url: '/pages/userHistoryMenu/userHistoryMenu?history=' + history,
        })
    },
    userCollectMenu() {
        wx.navigateTo({
            url: '/pages/userCollectMenu/userCollectMenu',
        })
    },
    toMyAttention() {
        wx.navigateTo({
            url: '/pages/myAttention/myAttention',
        })
    },
    toMemberInfoCenter() {
        let new_num = this.data.new_num;
        wx.setStorageSync('new_num', new_num)
        wx.navigateTo({
            url: `/pages/member-infoCenter/member-infoCenter`,
        })
    },
    toMemberPoints() {
        wx.navigateTo({
            url: '/pages/getJiFen/getJiFen',
        })
    },
    toMemberRecommendCode() {
        wx.navigateTo({
            url: '/pages/member-recommendCode/member-recommendCode',
        })
    },
    toMemberSongCoins() {
        wx.navigateTo({
            url: '/pages/member-songCoins/member-songCoins',
        })
    },
    //银歌币
    toMemberSongCoins2() {
        wx.navigateTo({
            url: '/pages/member-songCoins2/member-songCoins2',
        })
    },
    getCityId() {
        //比邻团，拿用户id和城市名称去获取城市id
        let obj = {
            id: wx.getStorageSync("user_id"),
            name: wx.getStorageSync("city_name")
        }
        http.request({
            url: api.getAddUserCityId,
            data: obj,
            success: res => {
                wx.setStorageSync("city_id", res.data.id);
            }
        })
    },
    toMemberNeighbor() {
        this.getCityId();
        wx.navigateTo({
            url: '/pages/member-neighbor/member-neighbor',
        })
    },
    toVipPage() {//去会员推广页面
        wx.navigateTo({
            url: '/pages/vippromotion/vippromotion',
        })
    },
    toMemberFriend() { //跳我的好友页面
        wx.navigateTo({
            url: '/pages/myfriend/myfriend',
        })
    },
    //去菜谱详情页面
    toVideo(e) {
        var id = e.target.dataset.id
        wx.navigateTo({
            url: "/pages/video/video?id=" + id
        })
    },
    toShop() {
        wx.navigateTo({
            url: "/pages/pointsMall/index/index"
        })
    },
    toShopRrsq() { // 跳转荣誉社区页面
        wx.navigateTo({
            url: "/pages/shop-rrsq/shop-rrsq"
        })
    },
    likesClick() {
        this.setData({
            is_auth: true,
            captureTouch: '',
            nickName: wx.getStorageSync("nickName"),
            avatarUrl: wx.getStorageSync("avatarUrl"),
        });
        let user_token = wx.getStorageSync('token');
        if (wx.getStorageSync('is_member') == 1) {
            this.setData({
                crown: true
            })
        } else {
            this.setData({
                crown: false
            })
        }

        if (user_token) {
            //获取歌豆积分
            this.getCoins(user_token)
        }

    },

    // 事件代理，用户未登录， 请先登录
    captureTouch(e) {
        console.log('????', e)
        let is_auth = this.data.is_auth;
        if (is_auth === false) {
            wx.showToast({
                title: '请先登录',
                mask: true,
                icon: "none",
                duration: 1500,
                success: () => {

                }
            })
        }
    },
    //拿到用户的金歌币数量没有则创建中间数据,必须调用
    getGoldGebiNumAdd(id) {
        http.request({
            url: api.getGoldGebiNumAdd,
            data: {
                id: id
            },
            success: (res) => {
                console.log(res)
                if (res.code == 200) {
                    this.setData({
                        new_gold_gebi_num: res.data.new_gold_gebi_num
                    })
                }
            }
        })
    },
    getGebiNumAdd(id) {
        http.request({
            url: api.getGebiNumAdd,
            data: {
                id: id
            },
            success: (res) => {
                console.log(res)
                if (res.code == 200) {
                    this.setData({
                        new_gebi_num: res.data.new_gebi_num
                    })
                }
            }
        })
    },
    getIntegralAdd(id) {
        http.request({
            url: api.getIntegralAdd,
            data: {
                id: id
            },
            success: (res) => {
                console.log(res)
                if (res.code == 200) {
                    this.setData({
                        new_integral_num: res.data.new_integral_num
                    })
                }
            }
        })
    },
    //获取用户的新消息数量
    getClientNewNum(id) {
        http.request({
            url: api.getClientNewNum,
            data: {
                id: id
            },
            success: (res) => {
                console.log(res)
                if (res.code == 200) {
                    this.setData({
                        new_num: res.data.new_num
                    })
                }
            }
        })
    },

    getHistroyBooks(id) {
        //获取曾经购买过的菜谱列表
        http.request({
            url: api.getBuyCookBook,
            data: {
                id: id
            },
            success: (res) => {
                if (res.msg == "该用户还没有买过菜谱") return
                this.setData({
                    history: res.data,
                    has: 1
                })
            }
        })
    },


    //晃动 动画
    bubbleAnimation() {
        // 1: 创建动画实例animation:
        let animation = wx.createAnimation({
            duration: 1500,
            timingFunction: 'linear',
        })
        this.animation = animation
        let next = true;
        //连续动画关键步骤
        setInterval(function () {
            //2: 调用动画实例方法来描述动画
            if (next) {
                animation.translateY(3).step();
                // animation.rotate(19).step()
                next = !next;
            } else {
                animation.translateY(-3).step();
                // animation.rotate(-19).step()
                next = !next;
            }
            this.setData({
                animation: animation.export()
            })
        }.bind(this), 600)
    },
    //页面发生滚动时
    onPageScroll: function (e) {
    },
    onPullDownRefresh: function (e) {
    },
    // 获取歌豆和积分明细
    getCoins(user_token) {
        console.log('11111111111111111111')
        http.request({
            url: api.accountCoins,
            data: {
                token: user_token
            },
            success: (res) => {
                console.log(res)
                if (res.code == 200) {
                    this.setData(res.data)
                }
            }
        })
    }
})